package com.ptmall.app.net.okhttp;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;

import com.facebook.stetho.common.LogUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ptmall.app.App;
import com.ptmall.app.AppApplication;
import com.ptmall.app.MainActivity;
import com.ptmall.app.R;
import com.ptmall.app.bean.model.db.Account;
import com.ptmall.app.net.HttpMethods;
import com.ptmall.app.net.base.BaseBean;
import com.ptmall.app.net.http.NetworkInterceptor;
import com.ptmall.app.net.http.NetworkResponseInterceptor;
import com.ptmall.app.view.MyProgressDialog;
import com.ptmall.app.view.ToastView;
import com.ptmall.app.view.ToastViewError;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by MacBook on 17/3/1.
 */

public class OkHttps extends BaseModel {
    private Context context;
    private OkHttpClient mOkHttpClient;
    private Gson gson;
    private MyProgressDialog mydialog;
    private ToastView toast;
    private ToastViewError toasts;
    private String APPAUTH;
    private final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mydialog.isShowing()) {
                mydialog.dismiss();
            }
            Log.i("zmh",msg.obj + "");
            switch (msg.what) {
                case 0:
//                    toast = new ToastView(mContext, (String) msg.obj);
//                    toast.setGravity(Gravity.CENTER, 0, 0);
//                    toast.show();
                    OkHttps.this.OnMessageResponse(msg.arg1, null);
                    break;
                case 1:
                    //完成主界面更新,拿到数据
                    //try{
                        OkHttps.this.OnMessageResponse(msg.arg1, (String) msg.obj);
                    /*}catch (Exception e){
                        toasts = new ToastViewError(mContext, "数据异常！");
                        toasts.setGravity(Gravity.CENTER, 0, 0);
                        toasts.show();
                    }*/

                    break;
                case 2:
//                    toasts = new ToastViewError(mContext, "请求失败！");
//                    toasts.setGravity(Gravity.CENTER, 0, 0);
//                    toasts.show();
                    OkHttps.this.OnMessageResponse(msg.arg1, null);
                    break;
                case 3:
//                    toasts = new ToastViewError(mContext, "请求异常！");
//                    toasts.setGravity(Gravity.CENTER, 0, 0);
//                    toasts.show();
                    OkHttps.this.OnMessageResponse(msg.arg1, null);
                    break;
            }
        }

    };

    public OkHttps(Context context) {
        super(context);
        this.context = context;
        gson  = new GsonBuilder()
                //.setLenient()// json宽松
                //.enableComplexMapKeySerialization()//支持Map的key为复杂对象的形式
                //.serializeNulls() //智能null
                //.setPrettyPrinting()// 调教格式
                .disableHtmlEscaping() //默认是GSON把HTML 转义的
                .create();
        mydialog = new MyProgressDialog(context, context.getResources().getString(R.string.hold_on));
        //创建okHttpClient对象
        mOkHttpClient = new OkHttpClient.Builder()
                //设置超时，不设置可能会报异常
                .connectTimeout(1000, TimeUnit.MINUTES)
                .readTimeout(1000, TimeUnit.MINUTES)
                .writeTimeout(1000, TimeUnit.MINUTES)
                .addInterceptor(new NetworkResponseInterceptor())//接口请求拦截器
                .addNetworkInterceptor(new NetworkInterceptor())
                .build();
        String guid = MainActivity.MEMBERID==null ? "" : MainActivity.MEMBERID;
        if (TextUtils.isEmpty(guid)) {
            guid = "";
        }
        APPAUTH = guid;

    }

    public Gson getGson() {
        return gson;
    }

    public void setProgressDialogTitle(String title){
        mydialog = new MyProgressDialog(context,title);
    }
    /**
     * 无参数的情况
     *
     * @return
     */
    public String getCanshuPaixu() {
        /*
        MyJSONObject json = new MyJSONObject();
        try {
            json.put(KEY_APPAUTH, APPAUTH);
            json.put(KEY_TIMESTAP, AllUtils.getTime());
            json.put(KEY_DEVICE,DEVICE_VALUE);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json.toString();
        */
        //排序用map
//        TreeMap<String, Object> map = new TreeMap();
//        map.put(KEY_APPAUTH, APPAUTH);
//        map.put(KEY_TIMESTAP, AllUtils.getTime());
//        map.put(KEY_DEVICE, DEVICE_VALUE);
//        String json = gson.toJson(map);
        String json = gson.toJson(HttpMethods.getInstance().getRequest(null,null).map);
        LogUtil.d("xucc","arg="+json);
        return json;
    }

    public String getCanshuPaixu(BaseBean param) {
//        //当前登录者信息
//        Account loginAccount = AppApplication.getInstance().getAccount();
//        param.setGuid(loginAccount == null ? "" : loginAccount.getAccessToken());
//        param.setTIMESTAMP(String.valueOf(System.currentTimeMillis() / 1000));
//
//        String arg = gson.toJson(param);
//
//
//
//        //重新排序
//        TreeMap<String, Object> map = gson.fromJson(arg, TreeMap.class);
//        map.put(KEY_DEVICE, DEVICE_VALUE);
//
//        //如果Value中有非String （比如特殊对象Object等）对象 则需要进行转成json格式字符串 防止出现toString 时 key=vaule的格式数据
//        for (Map.Entry<String, Object> entry : map.entrySet()) {
//            if (entry.getValue() instanceof String) {
//                map.put(entry.getKey(), entry.getValue());
//            } else {
//                map.put(entry.getKey(), gson.toJson(entry.getValue()).toString());
//            }
//        }
//
//        String json = gson.toJson(map);
        String json = gson.toJson(HttpMethods.getInstance().getRequest(param).map);
        LogUtil.d("xucc","arg="+json);
        //String sign = EAICoderUtil.getMD5Code(arg + KEY_ARG_SIGN);
        //map.put(KEY_SIGN,sign);
        return json;
    }

    /**
     * 自动排序
     *
     * @param keys
     * @param values
     * @return
     */
    public String getCanshuPaixu(String[] keys, String[] values) {

        /*
        String[] onekeys =new String[keys.length+2];
        String[] onevalues =new String[keys.length+2];
        onekeys[0] = KEY_APPAUTH;
        onevalues[0] = APPAUTH;
        onekeys[1] = KEY_TIMESTAP;
        onevalues[1] = AllUtils.getTime();
        int size = onekeys.length;
        for(int i = 0;i<keys.length;i++){//防止被排序重新赋值
            onekeys[i+2] = keys[i];
            onevalues[i+2] = values[i];
        }
        MyJSONObject json = new MyJSONObject();
        String[] newkeys =new String[size];
        String[] newvalues =new String[size];
        for(int i = 0;i<size;i++){//防止被排序重新赋值
            newkeys[i] = onekeys[i];
        }
        Arrays.sort(newkeys,String.CASE_INSENSITIVE_ORDER);
        for(int i = 0;i<size;i++){
            for(int j=0;j<size;j++){
                if(newkeys[i].equals(onekeys[j])){
                    newvalues[i] = onevalues[j];
                }
            }
        }
        for(int i = 0;i<size;i++){
            try {
                json.put(newkeys[i],newvalues[i]);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return json.toString();
        */
        //排序用map
//        TreeMap<String, Object> map = new TreeMap();
//        if (keys != null && values != null && keys.length == values.length && keys.length > 0) {
//            int count = keys.length;
//            for (int i = 0; i < count; i++) {
//                if (null != keys[i] && null != values[i]) {
//                    map.put(keys[i], values[i]);
//                }
//            }
//        }
//        long time = System.currentTimeMillis() / 1000;
//        map.put(KEY_TIMESTAP, String.valueOf(time));
//
//        if (!map.containsKey(KEY_APPAUTH)) {
//            Account loginAccount = AppApplication.getInstance().getAccount();
//            String guid = loginAccount==null ? "" : loginAccount.getAccessToken();
//            if (TextUtils.isEmpty(guid)) {
//                guid = "";
//            }
//            map.put(KEY_APPAUTH, guid);
//        }
//        map.put(KEY_DEVICE, DEVICE_VALUE);
//
//        String json = gson.toJson(map);
        String json = gson.toJson(HttpMethods.getInstance().getRequest(keys,values).map);
        LogUtil.d("xucc","arg="+json);
        return json;
    }

    /**
     * get请求
     *
     * @param url 网络请求地址
     * @param pd  是否出现加载动画
     * @param id  队列id
     */
    public void httpget(final String url, final boolean pd, final int id) {
        if (pd) {
            mydialog.show();
        }
        //创建一个Request
        final Request request = new Request.Builder()
                .url(url)
                .build();
        //new call
        Call call = mOkHttpClient.newCall(request);
        //请求加入调度
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message msg = new Message();
                msg.what = 2;
                msg.arg1 = id;
                mHandler.sendMessage(msg);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    callback(response.body().string(), id);
                } else {
                    //Log.i("zmh666",response.body().string());
                    Message msg = new Message();
                    msg.what = 3;
                    msg.arg1 = id;
                    mHandler.sendMessage(msg);
                }
            }
        });
    }

    /**
     * post请求
     *
     * @param url 网络请求地址
     * @param pd  是否出现加载动画
     * @param id  队列id
     */
    public void httppost(final String url, String json, final boolean pd, final int id) {
        LogUtil.d("xucc","url="+url);
        if (pd) {
            mydialog.show();
        }
        //创建一个Request
        Request request = new Request.Builder()
                .url(url)
                .post(getCanshu(json))
                .build();
        Call call = mOkHttpClient.newCall(request);
        //请求加入调度
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //e.printStackTrace();
                Message msg = new Message();
                msg.what = 2;
                msg.arg1 = id;
                mHandler.sendMessage(msg);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    callback(response.body().string(), id);
                } else {
                    Log.i("zmh666",response.body().string());
                    Message msg = new Message();
                    msg.what = 3;
                    msg.arg1 = id;
                    mHandler.sendMessage(msg);
                }
            }
        });
    }


    /**
     * 文件上传
     *
     * @param url 网络请求地址
     * @param pd  是否出现加载动画
     * @param id  队列id
     */
    public void postAsynFile(final String url, File file, final boolean pd, final int id) {
        if (pd) {
            mydialog.show();
        }
        final ProgressRequestListener progressListener = new ProgressRequestListener() {
            @Override
            public void onRequestProgress(long bytesWrite, long contentLength, boolean done) {
                Log.e("TAG", "bytesWrite:" + bytesWrite);
                Log.e("TAG", "contentLength" + contentLength);
                Log.e("TAG", (100 * bytesWrite) / contentLength + " % done ");
                Log.e("TAG", "done:" + done);
            }
        };
        RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        /*
        builder.addFormDataPart("arg", json.toString());
        builder.addFormDataPart("file", file.getName(),fileBody);
        builder.addFormDataPart("sign",EAICoderUtil.getMD5Code(json.toString()+ "asdf87290oiapso"));
        */
        /* 修改 Start */
//        Map<String, Object> map = gson.fromJson(json, Map.class);
//        String sign = EAICoderUtil.getMD5Code(json + KEY_ARG_SIGN);
//        if (null != map) {
//            map.put(KEY_SIGN, sign);
//            for (Map.Entry<String, Object> entry : map.entrySet()) {
//                builder.addFormDataPart(entry.getKey(), entry.getValue().toString());
//            }
//        }
        builder.addFormDataPart("token", HttpMethods.MEMBERID);
        builder.addFormDataPart("appid", "1002");
        builder.addFormDataPart("appkey", "dedSEr85sSkeld36DEs");
        builder.addFormDataPart("file", file.getName(), fileBody);
        /* 修改 End */

        //构建请求体
        RequestBody requestBody = builder.build();
        //创建一个Request
        Request request = new Request.Builder()
                .url(url)
//                .post(ProgressHelper.addProgressRequestListener(requestBody, progressListener))
                .post(requestBody)
                .build();
        Call call = mOkHttpClient.newCall(request);
        //请求加入调度
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message msg = new Message();
                msg.what = 2;
                msg.arg1 = id;
                mHandler.sendMessage(msg);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    callback(response.body().string(), id);
                } else {
                    Message msg = new Message();
                    msg.what = 3;
                    msg.arg1 = id;
                    mHandler.sendMessage(msg);
                }
            }
        });
    }


    /**
     * 多文件
     *
     * @param url 网络请求地址
     * @param pd  是否出现加载动画
     * @param id  队列id
     */
    public void postAsynFile(final String url, final String json, List<String> file, final boolean pd, final int id) {
        if (pd) {
            mydialog.show();
        }
   /*     final ProgressRequestListener progressListener = new ProgressRequestListener() {
            @Override
            public void onRequestProgress(long bytesWrite, long contentLength, boolean done) {
                Log.e("TAG", "bytesWrite:" + bytesWrite);
                Log.e("TAG", "contentLength" + contentLength);
                Log.e("TAG", (100 * bytesWrite) / contentLength + " % done ");
                Log.e("TAG", "done:" + done);
            }
        };*/
        //RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        /*
        builder.addFormDataPart("arg", json.toString());
        for (int i = 0; i <file.size() ; i++) {
            File f=new File(file.get(i));
            if (f!=null) {
                builder.addFormDataPart("file[]", f.getName(), RequestBody.create(MEDIA_TYPE_PNG, f));
            }
        }
        builder.addFormDataPart("sign",EAICoderUtil.getMD5Code(json.toString()+ "asdf87290oiapso"));
        */
        /* 修改 Start */
        Map<String, Object> map = gson.fromJson(json, Map.class);
//        String sign = EAICoderUtil.getMD5Code(json + KEY_ARG_SIGN);
        if (null != map) {
//            map.put(KEY_SIGN, sign);
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                builder.addFormDataPart(entry.getKey(), entry.getValue().toString());
            }
        }
        for (int i = 0; i < file.size(); i++) {
            File f = new File(file.get(i));
            if (f != null) {
                builder.addFormDataPart("file[]", f.getName(), RequestBody.create(MEDIA_TYPE_PNG, f));
            }
        }
        /* 修改 End */

        //构建请求体
        RequestBody requestBody = builder.build();
        //创建一个Request
        Request request = new Request.Builder()
                .url(url)
             //   .post(ProgressHelper.addProgressRequestListener(requestBody, progressListener))
                .post(requestBody)
                .build();
        Call call = mOkHttpClient.newCall(request);
        //请求加入调度
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message msg = new Message();
                msg.what = 2;
                msg.arg1 = id;
                mHandler.sendMessage(msg);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    callback(response.body().string(), id);
                } else {
                    Message msg = new Message();
                    msg.what = 3;
                    msg.arg1 = id;
                    mHandler.sendMessage(msg);
                }
            }
        });
    }

    /**
     * 获取处理后的参数
     *
     * @param json
     * @return
     */
    private RequestBody getCanshu(String json) {
      /*  String str= json.replace("\\", "");
        str = str.replace("\"{","{");
        str = str.replace("}\"","}");*/
        Log.i("canshu》》》》》", json);
        /*
        RequestBody formBody = new FormBody.Builder()
                .add("arg", json)
                .add("sign", EAICoderUtil.getMD5Code(json+ "asdf87290oiapso"))
                .build();
        return  formBody;
        */
        //反解析成Map
        LogUtil.d("xucc", "json=" + json);
        Map<String, Object> map = gson.fromJson(json, Map.class);
//        String sign = EAICoderUtil.getMD5Code(json + KEY_ARG_SIGN);
        FormBody.Builder builder = new FormBody.Builder();
        if (null != map) {
//            map.put(KEY_SIGN, sign);
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                /*
                LogUtil.d("xucc","vaue1="+entry.getValue().toString());
                LogUtil.d("xucc","vaue2="+gson.toJson(entry.getValue()));
                //builder.add(entry.getKey(),gson.toJson(entry.getValue()));
                if (entry.getValue() instanceof Map) {
                    //gson.toJson(entry.getValue());

                    builder.add(entry.getKey(),gson.toJson(entry.getValue()));
                } else {
                    builder.add(entry.getKey(),entry.getValue().toString());
                }
                */
                builder.add(entry.getKey(), entry.getValue().toString());
            }
        }
        return builder.build();
    }

    /**
     * 拦截器过滤不否和数据
     *
     * @param data
     * @return
     */
    public void callback(String data, int id) {
        Log.i("zmh", data);
        JSONObject object = null;
        Message msg = new Message();
        String status = "";
        try {
            //object = (JSONObject) new JSONTokener(data).nextValue();
            object = new JSONObject(data);
            status = object.getString("error");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (null != object) {
            if ("0".equals(status)) {
                //需要数据传递，用下面方法；
                msg.what = 1;
                msg.arg1 = id;
                try {
                    msg.obj = object.getJSONArray("data").toString();//可以是基本类型，可以是对象，可以是List、map等；
                } catch (JSONException e) {
                    e.printStackTrace();
                    try {
                        msg.obj = object.getJSONObject("data").toString();
                    } catch (JSONException e1) {
                        e1.printStackTrace();
                        try {
                            msg.obj = object.getString("data").toString();
                        } catch (JSONException e2) {
                            e2.printStackTrace();
                        }
                    }
                }
            } else {
                msg.what = 0;
                msg.arg1 = id;
                try {
                    msg.obj = object.getString("msg").toString();//可以是基本类型，可以是对象，可以是List、map等；
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        } else {
            msg.what = 3;
        }
        mHandler.sendMessage(msg);

    }
}
